package com.efounder.zone.view;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;

import com.efounder.zone.R;
import com.efounder.zone.adapter.ImageHorizontalSlideSelectAdapter;

import java.util.ArrayList;

public class ImageHorizontalSlideSelectView extends LinearLayout {

    private RecyclerView recyclerView;
    private ImageHorizontalSlideSelectAdapter imageHorizontalSlideSelectAdapter;
    private ArrayList<String> mPictureList = new ArrayList<>();

    public ImageHorizontalSlideSelectView(Context context) {
        this(context, null);
    }

    public ImageHorizontalSlideSelectView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.mobile_zone_image_horizontal_slide_select, this);
        recyclerView = findViewById(R.id.recyclerView);


        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        mPictureList = getAllPicture(context, 20);
        imageHorizontalSlideSelectAdapter = new ImageHorizontalSlideSelectAdapter(context, mPictureList);
        recyclerView.setAdapter(imageHorizontalSlideSelectAdapter);
    }

    public static ArrayList<String> getAllPicture(Context context, int maxCount) {
        String[] largeFileProjection = {
                MediaStore.Images.ImageColumns._ID,
                MediaStore.Images.ImageColumns.DATA,
                MediaStore.Images.ImageColumns.ORIENTATION,
                MediaStore.Images.ImageColumns.DATE_MODIFIED};
        String largeFileSort = MediaStore.Images.ImageColumns.DATE_MODIFIED + " DESC";
        Cursor cursor = context.getContentResolver()
                .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
        ArrayList<String> mFiles = new ArrayList<>();
        if (cursor == null) return mFiles;
        while (cursor.moveToNext()) {

            //获取图片的保存位置的数据
            byte[] data = cursor.getBlob(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            //将图片的保存位置的数据转换成字符串形式的路径
            String filePath = new String(data, 0, data.length - 1);
            if (maxCount != -1 && mFiles.size() >= maxCount) {
                break;
            }

            mFiles.add(filePath);
        }
        cursor.close();
        return mFiles;
    }
}
